//
// Created by 文道江 on 15/12/1.
// Copyright (c) 2015 文道江. All rights reserved.
//

#import "UpgradeManger.h"
#import "HybridBridge.h"


@implementation UpgradeManger

- (instancetype)initWithAppId:(NSString *)appId AppKey:(NSString *)apKey upgradeUrl:(NSString *)upgradeUrl {
    self = [super init];
    if (self) {
        self.appId = appId;
        self.upgradeUrl = upgradeUrl;
        self.appKey = apKey;
    }

    return self;
}


- (void) checkUpgrade:(BOOL(^)(BOOL newVersion, id info))newVersionCallback done:(void(^)(NSDictionary *versionInfo, NSError *error))callback{
    if (_upgradeUrl == nil){
        NSLog(@"未配置 UpgradeURL.");
        return;
    }

    //http://apps.50r.cn/index.php?s=/Home/Upgrade/check.html&app_id=%i&versionCode=%i&splashVersionCode=%i

    //NSString *urlString = [NSString stringWithFormat:_upgradeUrl, _appId, self.currentVersionCode, self.currentVersionCode];
    UIDevice *device = [UIDevice currentDevice];
    CGRect rx = [ UIScreen mainScreen ].bounds;
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSDictionary *params = @{
            @"appId": _appId,
            @"appKey": _appKey,
            @"webAppVerCode": @([self currentVersionCode]),
            @"version": infoDictionary[@"CFBundleShortVersionString"], // Native 版本
            @"versionCode": infoDictionary[@"CFBundleVersion"], // Native 版本号

            @"name": device.name,
            @"systemName": device.systemName,
            @"systemVersion": device.systemVersion,
            @"brand": @"Apple",
            @"model": device.model,
            @"screenWidth": @(rx.size.width),
            @"screenHeight": @(rx.size.height),
            @"uuid": device.identifierForVendor.UUIDString
    };

    [[URLSessionManager ajaxGET:_upgradeUrl params:params completionHandler:^(NSDictionary *data, NSError *error) {
        //NSLog(@"completionHandler : %@,%@", data, error);
        if (error == nil){
            if ([data[@"status"] boolValue]){
                NSDictionary *info = data[@"info"];
                if (info){

                    if (info[@"splashs"] && [info[@"splashs"] isKindOfClass:[NSArray class]]){
                        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:info[@"splashs"] options:NSJSONWritingPrettyPrinted error:nil];
                        [FZEasyFile writeFile:@"splash.json" contents:jsonData append:NO];
                        [self downloadSplashImages:info[@"splashs"] Callback:nil];
                    }

                    if (info[@"upgrade"]){
                        if (newVersionCallback && newVersionCallback(YES, info)){
                            [self downloadUpgrade:info[@"upgrade"] Callback:^(BOOL isSuccess) {
                                if (callback)callback(info, nil);
                            }];
                        }
                        return;
                    }
                }
            }
        }
        if (newVersionCallback) newVersionCallback(NO, data[@"info"]);
        if (callback)callback(data, error);
    }] resume];

}

- (void)downloadUpgrade:(NSDictionary *)upgrade Callback:(void(^)(BOOL isSuccess))callback{
    if (nil == upgrade || nil == upgrade[@"file"]){
        callback(NO);
        return;
    }

    NSDictionary *file = upgrade[@"file"];

    NSURLRequest *request = [URLSessionManager createRequestWithURLString:file[@"url"]];
    NSProgress *progress;
    NSURLSessionDownloadTask *downloadTask = [URLSessionManager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        if ([FZEasyFile isFileExists:[response suggestedFilename]]){
            [FZEasyFile removeFile:[response suggestedFilename]];
        }
        return [[NSURL alloc] initFileURLWithPath:[FZEasyFile fullFileName:[response suggestedFilename]]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if (error == nil){
            if (callback)callback([SSZipArchive unzipFileAtPath:filePath.relativePath toDestination:[FZEasyFile fullFileName:@"web"] overwrite:YES password:nil error:nil]);
        }else{
            if (callback)callback(NO);
        }
        [progress removeObserver:self forKeyPath:@"fractionCompleted"];
    }];

    [progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];

    [downloadTask resume];
}

- (void)downloadSplashImages:(NSArray *)splashs Callback:(void(^)(BOOL isSuccess))callback{
    if (splashs == nil || splashs.count == 0){
        if (callback)callback(NO);
        return;
    }

    for (NSUInteger i = 0; i < splashs.count; ++i) {
        NSDictionary *item = splashs[i];
        NSString *url = item[@"image"];
        if (url && ([url hasPrefix:@"http"] || [url hasPrefix:@"ftp"])){
            [self localPathWithURL:url];
        }
    }
    if (callback)callback(YES);
}

- (NSString *)localPathWithURL:(NSString *)url{
    if (url == nil)
        return nil;

    //需要手动建立目录splash
    if (![FZEasyFile isFileExists:@"splash/"]){
        [[NSFileManager defaultManager] createDirectoryAtPath:[FZEasyFile fullFileName:@"splash"] withIntermediateDirectories:YES attributes:nil error:nil];
    }

    NSString *path = [@"splash/" stringByAppendingString:[[CocoaSecurity md5:url].hexLower stringByAppendingFormat:@".%@", url.pathExtension]];
    if (![FZEasyFile isFileExists:path]){
        NSURLRequest *request = [URLSessionManager createRequestWithURLString:url];
        [[URLSessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            return [[NSURL alloc] initFileURLWithPath:[FZEasyFile fullFileName:path]];
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            NSLog(@"download path: %@ -- %@", path, error);
        }] resume];
    }
    return path;
}

+ (NSString *)getWebAppUrl{
    NSString *path = [FZEasyFile fullFileName:@"web/index.html"];

    NSString *versionPath = @"web/webapp_version.txt";
    NSInteger versionCode = [[HybridBridge defaultHybridBridge].appInfo[@"WebAppVersionCode"] integerValue];
    NSInteger oldVersionCode = 0;
    if (versionCode > 0 && [FZEasyFile isFileExists:versionPath]){
        oldVersionCode = [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:[FZEasyFile fullFileName:versionPath]] encoding:NSUTF8StringEncoding].integerValue;
    }

    if (![FZEasyFile isFileExists:@"web/index.html"] || ![FZEasyFile isFileExists:versionPath] || versionCode > oldVersionCode) {
        NSString *zipPath = [[NSBundle mainBundle] pathForResource:@"web" ofType:@"zip"];
        [SSZipArchive unzipFileAtPath:zipPath toDestination:[FZEasyFile fullFileName:@"web"]];
    }

    return [NSURL fileURLWithPath:path].absoluteString;
}

- (NSInteger)currentVersionCode {
    if (_currentVersionCode == 0){
        NSString *path = @"web/webapp_version.txt";
        if ([FZEasyFile isFileExists:path]){
            path = [FZEasyFile fullFileName:path];
            _currentVersionCode = [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:path] encoding:NSUTF8StringEncoding].integerValue;
        }
    }
    NSLog(@"_currentVersionCode : %d", _currentVersionCode);
    return _currentVersionCode;
}


#pragma mark observe

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
        NSProgress *progress = (NSProgress *)object;
        [[HybridEventBus defaultEventBus] postData:@{
                @"progress": progress
        } Tag:@"downloadUpgradeProgress"];
    }
}

@end
